﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Windows.Browser;

namespace MoneyBook.Interactivity {
    public class FocusBehavior : Behavior<FrameworkElement> {

        public Control Target {
            get { return (Control)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof(Control), typeof(FocusBehavior), new PropertyMetadata(OnTargetChanged));

        private static void OnTargetChanged(object sender, DependencyPropertyChangedEventArgs e) {

        }

        protected override void OnAttached() {
            if (this.AssociatedObject == null) {
                return;
            }
            this.AssociatedObject.Loaded += AssociatedObject_Loaded;
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e) {
            if (this.Target != null) {
                HtmlPage.Plugin.Focus();
                if (!this.Target.Focus()) {
                    Dispatcher.BeginInvoke(() => {
                        this.Target.Focus();
                    });
                }
            }
        }

        protected override void OnDetaching() {
            this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
        }
    }
}
